package com.github.rxyor.common.support.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.aop.framework.ReflectiveMethodInvocation;

/**
 *<p>
 * 简单的Aspect工具帮助类
 *</p>
 *
 * @author liuyang
 * @date 2019/3/6 Wed 20:16:00
 * @since 1.0.0
 */
@Slf4j
public class AspectHelper {

    /**
     * MethodInvocationProceedingJoinPoint对象字段名
     */
    private static final String JOIN_POINT_REFLECT_METHOD = "methodInvocation";

    private AspectHelper() {
    }

    public static Method getMethodOfJoinPoint(JoinPoint joinPoint) {
        assert joinPoint != null;
        Method method;

        try {
            MethodInvocationProceedingJoinPoint methodJoinPoint = (MethodInvocationProceedingJoinPoint) joinPoint;
            Field proxy = methodJoinPoint.getClass().getDeclaredField(JOIN_POINT_REFLECT_METHOD);
            if (!proxy.isAccessible()) {
                proxy.setAccessible(true);
            }
            ReflectiveMethodInvocation reflectiveMethodInvocation = (ReflectiveMethodInvocation) proxy.get(methodJoinPoint);
            method = reflectiveMethodInvocation.getMethod();
        } catch (Throwable e) {
            log.error("获取切点的Method失败,error:", e);
            throw new RuntimeException("获取切点的Method失败: " + e);
        }

        return method;
    }
}
